package Util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

import static Util.Rules.indicatorNameCleaning;
import static Util.UrlCollect.*;

public class SelectIndicator {

    public static String[][] priority = {
            {"（一年版）（分院报告）", "（分院报告）（一年版）", "（一年版）", "（分院报告）", ""},
            {"（一年版）", ""},
            {"（分院报告）", ""},

    };
    public static String[] t = {"（本科）", "（专科）"};

    public static JSONArray selectIndicatorObject(String req, String type) throws IOException {
        JSONArray res = new JSONArray();
        req=indicatorNameCleaning(req);
//        System.out.println(req);
        JSONArray jsonArray = select(req);
        List<String> list = getStrings(type, req, t, priority);
        for (String s : list) {
            for (Object o : jsonArray) {
                JSONObject jsonObject =(JSONObject) o;
                if (s.equals(jsonObject.getString("name"))) {
                    res.add(jsonObject);
                    return res;
                }
            }
        }
        return jsonArray;
    }


    public static List<String> getStrings(String type, String req, String t[], String priority[][]) {
        List<String> strings = new ArrayList<>();
        int index;

        if (type.contains("专科")) {
            index = 1;
        } else {
            index = 0;
        }

        if (type.contains("一年版") && type.contains("分院报告")) {
            addStrings(strings, req, t[index], priority[0]);
        } else if (type.contains("一年版")) {
            addStrings(strings, req, t[index], priority[1]);
        } else if (type.contains("分院报告")) {
            addStrings(strings, req, t[index], priority[2]);
        } else {
            strings.add(req + t[index]);
            strings.add(req);
        }

        return strings;
    }

    private static void addStrings(List<String> strings, String req, String t, String[] priority) {
        for (int i = 0; i < priority.length; i++) {
            strings.add(req + t + priority[i]);
            strings.add(req + priority[i]);
        }
    }

    public static JSONArray select(String requst) throws IOException {
        HttpUtil http = new HttpUtil();
        String a = "{\"isFuzzy\":true,\"name\":\"" + requst + "\",\"pageCount\":200,\"pageNum\":1,\"type\":\"通用\"}";
        return http.doBodyPost(SEARCH_METRIC_OBJECT_URL, a).getJSONObject("data").getJSONArray("data");
    }
}
